<template>
  <view class="video-detail-page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <text class="loading-text">加载视频详情中...</text>
    </view>

    <!-- 视频内容区 -->
    <view v-else v-if="JSON.stringify(videoInfo) !== '{}'">
      <!-- 视频播放容器（内联，不再依赖外部组件） -->
      <view class="video-player">
        <video
          :src="videoInfo.cover"
          :poster="videoInfo.cover"
          class="video-core"
          controls
          @play="handlePlay"
          @pause="handlePause"
        ></video>
        
        <!-- 视频信息栏 -->
        <view class="video-info-bar">
          <view class="left-info">
            <text class="video-title">{{ videoInfo.title }}</text>
            <text class="video-meta">
              {{ videoInfo.playCount }}次播放 · {{ videoInfo.duration }}
            </text>
          </view>
          
          <!-- 作者信息 + 关注按钮 -->
          <view class="author-info">
            <image 
              :src="getAuthorAvatar(videoInfo.author)" 
              class="author-avatar"
            ></image>
            <text class="author-name">{{ videoInfo.author }}</text>
            <button 
              class="follow-btn" 
              :class="{ followed: isFollowed }"
              @click.stop="toggleFollow"
            >
              {{ isFollowed ? '已关注' : '关注' }}
            </button>
          </view>
        </view>
        
        <!-- 操作栏（点赞/评论/分享） -->
        <view class="video-actions">
          <view class="action-item" @click.stop="toggleLike">
            <text class="action-icon like-icon" :class="{ liked: isLiked }">❤️</text>
            <text class="action-text">{{ likeCount }}</text>
          </view>
          <view class="action-item" @click.stop="gotoComment">
            <text class="action-icon">💬</text>
            <text class="action-text">{{ commentCount }}</text>
          </view>
          <view class="action-item" @click.stop="shareVideo">
            <text class="action-icon">↗️</text>
            <text class="action-text">分享</text>
          </view>
        </view>
      </view>

      <!-- 评论区 -->
      <view class="comment-section" v-if="videoInfo.comments && videoInfo.comments.length > 0">
        <view class="section-title">评论区 ({{ videoInfo.comments.length }})</view>
        <view class="comment-list">
          <view class="comment-item" v-for="comment in videoInfo.comments" :key="comment.id">
            <text class="comment-username">{{ comment.username }}</text>
            <text class="comment-time">{{ comment.time }}</text>
            <text class="comment-content">{{ comment.content }}</text>
          </view>
        </view>
      </view>

      <!-- 推荐视频区 -->
      <view class="recommend-section" v-if="videoInfo.recommend && videoInfo.recommend.length > 0">
        <view class="section-title">推荐视频</view>
        <view class="recommend-list">
          <view class="recommend-item" v-for="item in videoInfo.recommend" :key="item.id" @click="gotoRecommendVideo(item.id)">
            <text class="recommend-title">{{ item.title }}</text>
            <text class="recommend-playcount">{{ item.playCount }}次播放</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空数据状态 -->
    <view v-else class="empty-state">
      <text class="empty-icon">❌</text>
      <text class="empty-text">未找到该视频</text>
      <button class="back-btn" @click="uni.navigateBack()">返回上一页</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      videoId: '',
      videoInfo: {},
      isLiked: false,
      isFollowed: false,
      loading: true,
      likeCount: 0,
      commentCount: 0,
      app: null
    };
  },
  onLoad(options) {
    this.app = getApp();
    this.videoId = options.id || '';
    this.loadVideoDetail();
  },
  onShow() {
    this.syncVideoState();
  },
  methods: {
    loadVideoDetail() {
      try {
        this.loading = true;
        const videoData = this.app.globalData.videoData || {};
        
        // 优先读取详情，无详情则读取列表数据
        this.videoInfo = videoData.videoDetails?.[this.videoId] || 
                         videoData.videoList?.find(item => item.id == this.videoId) || 
                         {};
        
        // 初始化点赞数/评论数
        this.likeCount = this.videoInfo.playCount || '0';
        this.commentCount = this.videoInfo.comments?.length || 0;
        
        // 同步状态
        this.syncVideoState();
      } catch (e) {
        console.error('加载视频详情失败:', e);
        uni.showToast({ title: '视频详情加载失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },

    syncVideoState() {
      if (!this.app.globalData.userInfo) return;
      // 同步点赞状态
      this.isLiked = this.app.isContentLiked(this.videoId, 'video');
      // 同步关注状态
      this.isFollowed = this.app.isFollowed(this.videoInfo.author || '');
    },

    // 视频播放/暂停
    handlePlay() {
      console.log('视频开始播放：', this.videoId);
    },
    handlePause() {
      console.log('视频暂停播放：', this.videoId);
    },

    // 切换点赞
    toggleLike() {
      if (!this.checkLogin()) return;
      
      this.isLiked = !this.isLiked;
      // 同步到全局
      this.app.toggleVideoLike(this.videoId, this.isLiked);
      
      // 更新点赞数显示
      const num = Number(this.likeCount.replace(/[^\d]/g, ''));
      const newCount = this.isLiked ? num + 1 : Math.max(0, num - 1);
      this.likeCount = newCount >= 10000 
        ? `${(newCount / 10000).toFixed(1)}万` 
        : `${newCount}`;
      
      uni.showToast({
        title: this.isLiked ? '点赞成功' : '取消点赞',
        icon: 'none'
      });
    },
    
    // 切换关注作者
    toggleFollow() {
      if (!this.checkLogin()) return;
      
      this.isFollowed = !this.isFollowed;
      // 同步到全局
      this.app.toggleVideoAuthorFollow(this.videoInfo.author, this.isFollowed);
      
      uni.showToast({
        title: this.isFollowed ? '关注成功' : '取消关注',
        icon: 'none'
      });
    },
    
    // 跳转评论（预留）
    gotoComment() {
      uni.showToast({ title: '评论功能待完善', icon: 'none' });
    },
    
    // 分享视频
    shareVideo() {
      uni.showActionSheet({
        itemList: ['分享到微信', '分享到朋友圈', '复制链接'],
        success: (res) => {
          let tip = '';
          switch (res.tapIndex) {
            case 0: tip = '已分享到微信'; break;
            case 1: tip = '已分享到朋友圈'; break;
            case 2: tip = '链接已复制'; break;
          }
          uni.showToast({ title: tip, icon: 'none' });
        }
      });
    },
    
    // 登录校验
    checkLogin() {
      if (!this.app.globalData.userInfo) {
        uni.showModal({
          title: '提示',
          content: '请先登录后操作',
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({ url: '/pages/tabBar/tabcompage/login/login' });
            }
          }
        });
        return false;
      }
      return true;
    },
    
    // 作者头像（模拟）
    getAuthorAvatar(author) {
      const avatarMap = {
        '醉里挑灯看剑': '/static/avatar1.png',
        'NORA': '/static/avatar2.png',
        '动物大观察': '/static/avatar3.png'
      };
      // 兜底头像（确保路径存在，或替换为网络地址）
      return avatarMap[author] || 'https://via.placeholder.com/60x60';
    },

    // 跳转到推荐视频
    gotoRecommendVideo(recommendId) {
      uni.navigateTo({
        url: `/pages/tabBar/video/video-detail/video-detail?id=${recommendId}`,
        fail: (err) => {
          console.error('推荐视频跳转失败：', err);
          uni.showToast({ title: '跳转失败', icon: 'none' });
        }
      });
    }
  }
};
</script>

<style scoped>
.video-detail-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 加载状态 */
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
}
.loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  color: #999;
}
.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}
.empty-text {
  font-size: 28rpx;
  margin-bottom: 30rpx;
}
.back-btn {
  padding: 10rpx 40rpx;
  border-radius: 30rpx;
  background: #d00000;
  color: #fff;
  font-size: 24rpx;
}

/* 视频播放容器 */
.video-player {
  background: #fff;
  border-radius: 15rpx;
  overflow: hidden;
  margin-bottom: 20rpx;
}
.video-core {
  width: 100%;
  height: 400rpx;
}

/* 视频信息栏 */
.video-info-bar {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}
.left-info {
  margin-bottom: 10rpx;
}
.video-title {
  font-size: 30rpx;
  font-weight: 500;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.video-meta {
  font-size: 24rpx;
  color: #999;
}

/* 作者信息 */
.author-info {
  display: flex;
  align-items: center;
  gap: 15rpx;
}
.author-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
}
.author-name {
  font-size: 26rpx;
  color: #333;
  flex: 1;
}
.follow-btn {
  padding: 8rpx 20rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  background: #d00000;
  color: #fff;
  transition: all 0.3s ease;
}
.follow-btn.followed {
  background: #999;
}
.follow-btn:active {
  transform: scale(0.95);
  opacity: 0.8;
}

/* 操作栏 */
.video-actions {
  display: flex;
  justify-content: center;
  gap: 60rpx;
  padding: 15rpx 0;
  border-top: 1rpx solid #f0f0f0;
}
.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  padding: 10rpx;
  border-radius: 10rpx;
  transition: all 0.2s ease;
}
.action-item:active {
  background: #f5f5f5;
  transform: scale(0.95);
}
.action-icon {
  font-size: 36rpx;
}
.like-icon {
  transition: all 0.3s ease;
}
.like-icon.liked {
  color: #ff4444;
  transform: scale(1.1);
  animation: pulse 0.5s ease;
}
.action-text {
  font-size: 24rpx;
  color: #666;
}

/* 评论区 */
.comment-section {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
}
.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid #f0f0f0;
}
.comment-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}
.comment-item {
  padding: 10rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}
.comment-username {
  font-size: 24rpx;
  font-weight: 500;
  color: #333;
  display: block;
  margin-bottom: 5rpx;
}
.comment-time {
  font-size: 20rpx;
  color: #999;
  margin-right: 15rpx;
}
.comment-content {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
  display: block;
  margin-top: 5rpx;
}

/* 推荐视频区 */
.recommend-section {
  background-color: #fff;
  padding: 20rpx;
}
.recommend-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}
.recommend-item {
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  cursor: pointer;
}
.recommend-title {
  font-size: 26rpx;
  color: #333;
  display: block;
  margin-bottom: 5rpx;
}
.recommend-playcount {
  font-size: 22rpx;
  color: #999;
}

/* 点赞动画 */
@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1.1); }
}
</style>